package com.jsnkj.basic.config

import android.app.Activity
import android.net.Uri
import com.jsnkj.basic.util.SharePreferencesUtil
import com.umeng.umlink.MobclickLink
import com.umeng.umlink.UMLinkListener

object UMengManager {

    val KEY_GET_INSTALL_PARAMS = "key_Has_Get_InstallParams"

    private var uMLinkListener: UMLinkListener? = null

    private var mInstall_params: HashMap<String, String> = HashMap<String, String>()

    fun getUMLinkListener(activity: Activity): UMLinkListener {
        if (null == uMLinkListener) {
            uMLinkListener = object : UMLinkListener {
                override fun onLink(path: String, query_params: HashMap<String, String>) {
                    var itemStr = "分享得到数据：\n path == $path"
                    for (key in query_params.keys) {
                        itemStr += "\n  key = " + key + " value =" + query_params[key]
                    }
                    com.jsnkj.basic.util.LogUtils.e("分享", "得到数据：${itemStr}")
                    showDialog(activity, itemStr)
                    query_params["pid"]?.let {
                        SharePreferencesUtil.getInstance().putString("pid", it)
                    }

                    query_params["group"]?.let {
                        SharePreferencesUtil.getInstance().putString("group_invite", it)
                    }

                    query_params["cid"]?.let {
                        SharePreferencesUtil.getInstance().putString("cid", it)
                    }
                }

                override fun onInstall(install_params: HashMap<String, String>, uri: Uri) {
                    if (install_params.isEmpty() && uri.toString().isEmpty()) {
                        showDialog(activity, "没有匹配到安装参数")
                    } else {
                        if (install_params.isNotEmpty()) {
                            mInstall_params = install_params
                        }
                        if (uri.toString().isNotEmpty()) {
                            MobclickLink.handleUMLinkURI(activity, uri, uMLinkListener)
                        }
                    }

                    SharePreferencesUtil.getInstance().putBoolean(KEY_GET_INSTALL_PARAMS, true)
                }

                override fun onError(error: String) {
                    com.jsnkj.basic.util.LogUtils.e("友盟分享 异常：$error")
                    showDialog(activity, error)
                }
            }
        }
        return uMLinkListener!!
    }

    fun showDialog(activity: Activity, message: String) {
        try {
//            if (!activity.isFinishing) {
//                val builder = AlertDialog.Builder(activity)
//                builder.setMessage(message)
//                builder.setNegativeButton("OK") { dialog, whichButton -> }
//                builder.show()
//            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

}